package com.pwt.service;

import com.pwt.common.CustomException;
import com.pwt.common.ResultCode;
import com.pwt.entity.*;
import com.pwt.model.WhatResultModel;
import com.pwt.model.WhatResultVoModel;
import com.pwt.repository.*;
import com.pwt.security.utils.JWTUtils;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * WhatResult service层
 *
 * @author auto generated
 * @date 2021-09-04 11:50:49
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class WhatResultService {

    private WhatResultRepository whatResultRepository;

    private WhatAttributeRepository whatAttributeRepository;

    private WhatStatisticsRepository whatStatisticsRepository;

    private ProductAttributeRepository productAttributeRepository;

    private ProductStatisticsRepository productStatisticsRepository;

    private JPAQueryFactory jpaQueryFactory;


    public WhatResultService(WhatResultRepository whatResultRepository, WhatAttributeRepository whatAttributeRepository, WhatStatisticsRepository whatStatisticsRepository, ProductAttributeRepository productAttributeRepository, ProductStatisticsRepository productStatisticsRepository, JPAQueryFactory jpaQueryFactory) {
        this.whatResultRepository = whatResultRepository;
        this.whatAttributeRepository = whatAttributeRepository;
        this.whatStatisticsRepository = whatStatisticsRepository;
        this.productAttributeRepository = productAttributeRepository;
        this.productStatisticsRepository = productStatisticsRepository;
        this.jpaQueryFactory = jpaQueryFactory;
    }

    public List<WhatResult> getGlobalList(){
        //全局配置
        return this.whatResultRepository.findByGlobal(1);
    };

    public List<WhatResult> getUserList(){
        String username = JWTUtils.getToken().getUsername();
        List<WhatResult> byCreateByIn = this.whatResultRepository.findByCreateBy(username);
        return byCreateByIn;
    };

    public List<WhatResult> getList(){
        String username = JWTUtils.getToken().getUsername();
        List<WhatResult> byCreateByIn = this.whatResultRepository.findByCreateBy(username);
        List<WhatResult> all = getGlobalList();
        all.addAll(byCreateByIn);
        return all;
    }


    public WhatResult add(WhatResultModel whatResultModel) throws CustomException {
        WhatResult whatResult = null;
        if(StringUtils.isBlank(whatResultModel.getId())){
             whatResult = new WhatResult();
        }else{
            throw new CustomException(ResultCode.PARAM_IS_INVALID);
        }
        whatResult.setName(whatResultModel.getName());
        whatResult.setGlobal(whatResultModel.getGlobal());
        this.whatResultRepository.save(whatResult);
        if(StringUtils.isNotBlank(whatResultModel.getAttributeIds())){
            String[] attributeIds = whatResultModel.getAttributeIds().split(",");
            List<WhatAttribute> attributeList = new ArrayList<>();
            for (int i = 0; i < attributeIds.length; i++) {
                WhatAttribute whatAttribute = new WhatAttribute();
                whatAttribute.setWhatResultId(whatResult.getId());
                whatAttribute.setProductAttributeId(attributeIds[i]);
                attributeList.add(whatAttribute);
            }
            this.whatAttributeRepository.saveAll(attributeList);
        }
        if(StringUtils.isNotBlank(whatResultModel.getStatisticsIds())){
            String[] statisticsIds = whatResultModel.getStatisticsIds().split(",");
            List<WhatStatistics> statisticsList = new ArrayList<>();
            for (int i = 0; i < statisticsIds.length; i++) {
                WhatStatistics whatStatistics = new WhatStatistics();
                whatStatistics.setWhatResultId(whatResult.getId());
                whatStatistics.setProductStatisticsId(statisticsIds[i]);
                statisticsList.add(whatStatistics);
            }
            this.whatStatisticsRepository.saveAll(statisticsList);
        }

        return whatResult;
    }


    public WhatResult update(WhatResultModel whatResultModel) throws CustomException {
        if(StringUtils.isBlank(whatResultModel.getId())){
            throw new CustomException(ResultCode.PARAM_IS_INVALID);
        }
        WhatResult whatResult = this.whatResultRepository.getById(whatResultModel.getId());
        if(whatResult == null){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        whatResult.setName(whatResultModel.getName());
        whatResult.setGlobal(whatResultModel.getGlobal());
        this.whatResultRepository.save(whatResult);
        if(StringUtils.isNotBlank(whatResultModel.getAttributeIds())){
            String[] attributeIds = whatResultModel.getAttributeIds().split(",");
            List<WhatAttribute> attributeList = new ArrayList<>();
            if(attributeIds != null && attributeIds.length > 0 ){
                for (int i = 0; i < attributeIds.length; i++) {
                    WhatAttribute whatAttribute = new WhatAttribute();
                    whatAttribute.setWhatResultId(whatResult.getId());
                    whatAttribute.setProductAttributeId(attributeIds[i]);
                    attributeList.add(whatAttribute);
                }
            }
            this.whatAttributeRepository.deleteByWhatId(whatResult.getId());
            this.whatAttributeRepository.saveAll(attributeList);
        }


        if(StringUtils.isNotBlank(whatResultModel.getStatisticsIds())){
            String[] statisticsIds = whatResultModel.getStatisticsIds().split(",");
            List<WhatStatistics> statisticsList = new ArrayList<>();
            if(statisticsIds != null && statisticsIds.length > 0 ){
                for (int i = 0; i < statisticsIds.length; i++) {
                    WhatStatistics whatStatistics = new WhatStatistics();
                    whatStatistics.setWhatResultId(whatResult.getId());
                    whatStatistics.setProductStatisticsId(statisticsIds[i]);
                    statisticsList.add(whatStatistics);
                }
            }
            this.whatStatisticsRepository.deleteByWhatId(whatResult.getId());
            this.whatStatisticsRepository.saveAll(statisticsList);
        }
        return whatResult;
    }

    public WhatResultVoModel getWhatResultById(String id) throws CustomException {
        WhatResult whatResult = this.whatResultRepository.findById(id).orElse(null);
        if(whatResult == null){
            throw  new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        WhatResultVoModel whatResultVoModel = new WhatResultVoModel();
        whatResultVoModel.setWhatResultId(whatResult.getId());
        whatResultVoModel.setWhatResultName(whatResult.getName());
        whatResultVoModel.setSelectedAttribute(new ArrayList<>());
        whatResultVoModel.setUnselectedAttribute(new ArrayList<>());
        whatResultVoModel.setSelectedStatistics(new ArrayList<>());
        whatResultVoModel.setUnselectedStatistics(new ArrayList<>());
        List<String> attributeList = this.whatAttributeRepository.findByWhatResultId(whatResult.getId());
        List<ProductAttribute> productAttributeList = this.productAttributeRepository.findAll();
        if(attributeList != null && productAttributeList != null){
            for (ProductAttribute productAttribute:productAttributeList) {
                int i = 0;
                for (String whatAttribute:attributeList) {
                    if(whatAttribute.equals(productAttribute.getId())){
                        whatResultVoModel.getSelectedAttribute().add(productAttribute);
                        i = 1;
                    }
                }
                if(i == 0){
                    whatResultVoModel.getUnselectedAttribute().add(productAttribute);
                }
            }

        }
        List<WhatStatistics>  statisticsList = this.whatStatisticsRepository.findByWhatResultId(whatResult.getId());
        List<ProductStatistics> productStatisticsList = this.productStatisticsRepository.findAll();
        if(statisticsList != null && productStatisticsList != null){
            for (ProductStatistics productStatistics:productStatisticsList) {
                int i = 0;
                for (WhatStatistics whatStatistics:statisticsList) {
                    if(whatStatistics.getProductStatisticsId().equals(productStatistics.getId())){
                        whatResultVoModel.getSelectedStatistics().add(productStatistics);
                        i = 1;
                    }
                }
                if(i == 0){
                    whatResultVoModel.getUnselectedStatistics().add(productStatistics);
                }
            }

        }
        return whatResultVoModel;
    }


    public WhatResult copyWhatResult(String id) throws CustomException {
        WhatResult whatResult = this.whatResultRepository.getById(id);
        if(whatResult == null){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        WhatResult copyWhatResult = new WhatResult();
        copyWhatResult.setName(whatResult.getName());
        copyWhatResult.setGlobal(whatResult.getGlobal());
        this.whatResultRepository.save(copyWhatResult);
        List<String> byWhatResultId = this.whatAttributeRepository.findByWhatResultId(id);
        List<WhatAttribute> newList = new ArrayList<>();
        if(byWhatResultId != null){
            for (int i = 0; i < byWhatResultId.size(); i++) {
                WhatAttribute whatAttribute = new WhatAttribute();
                whatAttribute.setWhatResultId(copyWhatResult.getId());
                whatAttribute.setProductAttributeId(byWhatResultId.get(i));
                newList.add(whatAttribute);
            }
            this.whatAttributeRepository.saveAll(newList);
        }
        List<WhatStatistics> byWhatStatistics = this.whatStatisticsRepository.findByWhatResultId(id);
        List<WhatStatistics> newStatisticsList = new ArrayList<>();
        if(byWhatStatistics != null){
            for (int i = 0; i < byWhatStatistics.size(); i++) {
                WhatStatistics whatStatistics = new WhatStatistics();
                whatStatistics.setWhatResultId(copyWhatResult.getId());
                whatStatistics.setProductStatisticsId(byWhatStatistics.get(i).getProductStatisticsId());
                newStatisticsList.add(whatStatistics);
            }
            this.whatStatisticsRepository.saveAll(newStatisticsList);
        }
        return copyWhatResult;
    }


    public void delete(String id){
        this.whatResultRepository.deleteById(id);
        this.whatAttributeRepository.deleteByWhatId(id);
        this.whatStatisticsRepository.deleteByWhatId(id);
    }

    //获取已选图例
    public List<ProductAttribute> getProductAttributeList(String whatResultId){
        List<String> list = this.whatAttributeRepository.findByWhatResultId(whatResultId);
        QProductAttribute qProductAttribute = QProductAttribute.productAttribute;
        List<ProductAttribute> attributesList = jpaQueryFactory.select(qProductAttribute).from(qProductAttribute).where(qProductAttribute.id.in(list)).fetch();
        return attributesList;
    }

    //获取选择统计
    public List<ProductStatistics> getProductStatisticsList(String whatResultId){
        List<String> list = this.whatStatisticsRepository.findStatisticsByWhatResultId(whatResultId);
        QProductStatistics qProductStatistics = QProductStatistics.productStatistics;
        List<ProductStatistics> statisticsList = jpaQueryFactory.select(qProductStatistics).from(qProductStatistics).where(qProductStatistics.id.in(list)).fetch();
        return statisticsList;
    }
}
